﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Runtime.Serialization;
using System.IO.IsolatedStorage;
using TweetSharp;


namespace BankProject
{
    public partial class Page2 : PhoneApplicationPage
    {
        //Twitter
        //private const string consumerKey = "eH36i3QHl3Qxp4eYc8HEQ";
        //private const string consumerSecret = "tqyIwxoIZ8dpjZ4814Ku2lma7apTdmmslUVRT8lmUs";
        
        
        //private bool userAuthenticated = false;



        List<Banks> banks = new List<Banks>();
        List<Tag> Tags_ = new List<Tag>();
        string s;
        string s2;
        public Page2()
        {
            InitializeComponent();

            
            DataContext = App.ViewModel;
            listPicker1.IsEnabled = false;
            banks = LoadFromFile<List<Banks>>("banks.xml");
            Tags_ = LoadFromFile<List<Tag>>("tags.xml");
            if (banks == null) BanksAdd();
            if (Tags_ == null) AddTags();
            foreach (var item in banks)
            {
                listPicker1.Items.Add(item.Name);
            }
            int i = 0;
            foreach (var item in this.stackpanel3.Children)
            {
                if (item is CheckBox)
                {
                    ((CheckBox)item).Content = Tags_[i].Name;
                    i++;
                }
            }
        }

        //private void processRequestToken(OAuthRequestToken token, TwitterResponse response)
        //{
        //    if (token == null)
        //        Dispatcher.BeginInvoke(() => { MessageBox.Show("Error getting request token"); });
        //    else
        //    {
        //        requestToken = token;
        //        Dispatcher.BeginInvoke(() =>
        //        {
        //            Browser.Visibility = System.Windows.Visibility.Visible;
        //            Browser.Navigate(App.ViewModel.CLient.GetAuthorizationUri(requestToken));
        //        });
        //    }
        //}

        // получай доступ ко всем полям с помощью App.ViewModel.Review.Check1 и т.д.

        void BanksAdd()
        {
            banks = new List<Banks>();
            
            banks.Add( new Banks { Name = "ПриватБанк" }); 
            banks.Add( new Banks { Name = "АльфаБанк" }); 
            banks.Add( new Banks { Name = "Пумб" }); 
            banks.Add( new Banks { Name = "Астра Банк" }); 
            banks.Add( new Banks { Name = "Базис" }); 
            banks.Add( new Banks { Name = "Мегабанк" }); 
            banks.Add( new Banks { Name = "Надра Банк" }); 
            banks.Add( new Banks { Name = "СоцКомБанк" }); 
            banks.Add( new Banks { Name = "Синтез" }); 
            banks.Add( new Banks { Name = "Трансбанк" }); 
            banks.Add( new Banks { Name = "Укрпромбанк" }); 
            banks.Add( new Banks { Name = "Укрэксимбанк" }); 
            banks.Add( new Banks { Name = "Укрпромбанк" }); 
            banks.Add( new Banks { Name = "Райффайзен Банк Аваль" }); 
            banks.Add( new Banks { Name = "Укргазбанк" }); 
        

            SaveToFile("banks.xml", banks);
        }

        void AddTags()
        {
            Tags_ = new List<Tag>() {
                new Tag { Name = "Сердитые клиенты", Tag_ = "angrycustomers"},
                new Tag { Name = "Нет стульев", Tag_ = "nochairs"},
                new Tag { Name = "День пенсии", Tag_ = "daypensions"},
                new Tag { Name = "Хамы в очереди", Tag_ = "Loutsinqueue"},
                new Tag { Name = "Наглая кассирша", Tag_ = "insolentcashier"},
                new Tag { Name = "Нерастаропные кассиры", Tag_ = "retardedteller"},
                new Tag { Name = "Ограбление", Tag_ = "robbery"}
            };
            SaveToFile("tags.xml", Tags_);
        }

        private void checkBox_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            textBox1.IsEnabled = false;
            listPicker1.IsEnabled = true;
        }

        private void checkBox_Unchecked(object sender, System.Windows.RoutedEventArgs e)
        {
            textBox1.IsEnabled = true;
            listPicker1.IsEnabled = false;
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)//Отправить
        {

            //If user is already logged in, just send the tweet, otherwise get the RequestToken
            if (App.ViewModel.userAuthenticated)
            {
                //send the Tweet, this is just a placeholder, we will add the actual code later
                Dispatcher.BeginInvoke(() =>
                {
                    App.ViewModel.CLient.SendTweet("", (twitterStatus, twitterResponse) =>
                        {
                            //после отпрвки
                        });
                });
            }
            else
                NavigationService.Navigate(new Uri("/Views/TwitterPage.xaml", UriKind.Relative));
                

            bool b= false;
            if (textBox1.IsEnabled && banks != null)
            {
                for (int i = 0; i < banks.Count; i++)
                {
                    if (banks[i].Name.ToLower() == textBox1.Text.ToLower())
                    {
                        b = true;
                        break;
                    }
                }
                if (b == false)
                {
                    banks.Add(new Banks() { Name = textBox1.Text });
                }
                if (textBox1.IsEnabled)
                {
                    SaveToFile("banks.xml", banks);
                    SaveToFile("viev.xml", App.ViewModel);
                }
            }
        }

        public static void SaveToFile(string path, object objForSave)
        {
            using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(path, FileMode.OpenOrCreate, App.Store))
            {

                Serialize(file, objForSave);
                file.Close();
            };
        }

        public static T LoadFromFile<T>(string path)
        {
            T obj = default(T);

            if (!App.Store.FileExists(path)) return obj;

            using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, App.Store))
            {
                obj = (T)Deserialize(file, typeof(T));

                file.Close();
            };

            return obj;
        }

        private static void Serialize(Stream streamObject, object objForSerialization)
        {
            if (objForSerialization == null || streamObject == null)
                return;

            DataContractSerializer ser = new DataContractSerializer(objForSerialization.GetType());
            ser.WriteObject(streamObject, objForSerialization);
        }

        private static object Deserialize(Stream streamObject, Type serializedObjectType)
        {
            if (serializedObjectType == null || streamObject == null)
                return null;
            try
            {
                DataContractSerializer ser = new DataContractSerializer(serializedObjectType);
                return ser.ReadObject(streamObject);
            }
            catch { return null; }
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            FormingString();
        }

        private void listPicker1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            FormingString();
        }

        void FormingString()
        {
            if((bool)checkBox.IsChecked) textBox1.Text = listPicker1.SelectedItem.ToString();
            if (textBox1.Text.Length > 0 || textBox2.Text.Length > 0 || textBox3.Text.Length > 0 || textBox4.Text.Length > 0 || textBox5.Text.Length > 0)
            {
                s2 = String.Format("#ihatetowait @{0} #{1}inline #{2}mtowait #{3}avail #{4}closed", textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text);
                StringText.Text = s2 + s;
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            s = "";
            int i = 0;
            try
            {
                foreach (var item in this.stackpanel3.Children)
                {
                    if (item is CheckBox)
                    {
                       if((bool)((CheckBox)item).IsChecked) s += String.Format(" {0}", Tags_[i].Tag_);
                       i++;
                    }
                }
            }
            catch (Exception x) { Console.WriteLine(x.Message); }

            StringText.Text = s2 + s;
        }

        //private void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        //{
        //    if (e.Uri.AbsoluteUri.Contains("oauth_verifier"))
        //    {
        //        var values = ParseQueryString(e.Uri.AbsoluteUri);
        //        string verifier = values["oauth_verifier"];
        //        App.ViewModel.CLient.GetAccessToken(requestToken, verifier, processAccessToken);
        //        Dispatcher.BeginInvoke(() => { Browser.Visibility = System.Windows.Visibility.Collapsed; });
        //    }
        //}

        //// From Hammock.Extensions.StringExtensions.cs
        //public static IDictionary<string, string> ParseQueryString(string query)
        //{
        //    // [DC]: This method does not URL decode, and cannot handle decoded input
        //    if (query.StartsWith("?")) query = query.Substring(1);
        //    if (query.Equals(string.Empty))
        //    {
        //        return new Dictionary<string, string>();
        //    }
        //    var parts = query.Split(new[] { '&' });
        //    return parts.Select(
        //        part => part.Split(new[] { '=' })).ToDictionary(
        //            pair => pair[0], pair => pair[1]
        //        );
        //}

        //private void processAccessToken(OAuthAccessToken token, TwitterResponse response)
        //{
        //    if (token == null)
        //        Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); });
        //    else
        //    {
        //        App.ViewModel.CLient.AuthenticateWith(token.Token, token.TokenSecret);
        //        userAuthenticated = true;
        //        //Send the Tweet, we will add this code later
        //    }
        //}

        //private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
        //{
        //    if (response.StatusCode == HttpStatusCode.OK)
        //        Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); });
        //    else
        //        Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); });
        //}

    }
}